import * as filesService from '@/services/FilesService.js'
import * as orgService from '@/services/OrganizationService'
import moment from 'moment'

export default {
  data: function () {
    return {
      groupxname: '',
      groupsearch: '',
      time: '',
      groupname: '',
      groupname1: '',
      plantabs: 'first',
      adddialog: false,
      duty_name: '',
      pFilter: '',
      gFilter: '',
      checkedTimes: '',
      content: '',
      starttime: '',
      endtime: '',
      gOptions: [],
      pOptions: [],
      asd: true,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      startOptions: {
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      endOptions: {
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      thead1: [{
        name: '值班组名称',
        prop: 'groupx_name',
        width: '140'
      },
        {
          name: '值班开始时间',
          prop: 'starttime',
          width: '150'
        },
        {
          name: '值班结束时间',
          prop: 'endtime',
          width: '150'
        },
        {
          name: '值班组人员',
          prop: 'name'
        },
        {
          name: '创建人',
          prop: 'creatName',
          width: '100'
        },
      ],
      nightShift: [],
      whiteShift: [{
        'd_id': '1',
        stafftime: []
      }],
      times: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      sOptions: [],
      toptions: [{
        name: '编辑',
        prop: 'edit'
      }, {
        name: '查看',
        prop: 'look'
      }],
      currentPage: 1,
      currentPage1: 1,
      ddid: '',
      id: '',
      page: 1,
      shipSize: 0,
      totalPage: 0,
      stafftime: [],
      username: '',
      dutyname: '',
      dialogWidth: '80%',
      aadmin: JSON.parse(localStorage.getItem('admin')),
      asdFalse: false,
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      },
      activeName2: '0',
      sos: [],
      level1: -1,
      level2: -1,
      level3: -1,
      fheight: '400px',
      distance: '',
      uploadobj: {
        filename: '',
        mimeType: 'application/vnd.ms-excel',
        bus: 'duty',
        orgId: this.$profile.organiza.id,
        busId: 0,
        bussinessId: 1
        // skey: localStorage.getItem('auth')
        // appid: '135',
        // businessobj: 'txt'
      },
      uploadUrl: '',
      fileList: []
    }
  },
  // created () {
  //
  // },
  created () {
    this.getNewData()
    // this.username = localStorage.getItem('cu_id')
  },
  methods: {
    getNewData () {
      var that = this
      var list1 = [], list2 = [], list3 = [], list4 = [], ids = []
      orgService.findAll().then(async res => {
        res.data.forEach(item => {
          ids.push(item.id)
        })
        await res.data.sort((a, b) => {
          if(a.businessOrg < b.businessOrg){
            return -1
          }
          if(a.businessOrg > b.businessOrg){
            return 1
          }
          return 0
        })
        return res.data
      }).then(resp => {
        filesService.searchAll('organiza.id=in=' + ids.join(',')).then(res => {
          resp.forEach(item => {
            let arr = []
            res.data.forEach(ele => {
              if (item.id == ele.organiza.id && that.activeName2 == ele.bussinessId) {
                arr.push(ele) // item.files
              }
            })
            item.files = arr
            if (item.type == '内设处室') { // 内设处室
              list1.push(item)
            } else if (item.type == '处室办事机构') { // 处室办事机构
              list2.push(item)
            } else if (item.type == '直属单位') { // 直属单位
              list3.push(item)
            } else if (item.type == '派出机构') { // 派出机构
              list4.push(item)
            }
          })
        }).then(res => {
          that.sos.push({name: '内设处室', sub: list1})
          that.sos.push({name: '处室办事机构', sub: list2})
          that.sos.push({name: '直属单位', sub: list3})
          that.sos.push({name: '派出机构', sub: list4})
        })
      })
    },
    deleteDuty (id) {
      filesService.deleteById(id).then(res => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    detail (val) {
      window.open(this.$config['imgUrl'] + val)
    },
    getNight (val) {
      this.$axios.get(this.$config['searchNight'], {
        params: {
          skey: localStorage.getItem('auth'),
          counts: 10,
          page: val || 1,
          date: this.time,
          usernames: this.dutyname,
          dId: this.groupxname,
        }
      }).then((res) => {
        this.nightShift = res.data.content.ships
        this.totalPage = res.data.content.shipSize

      })
    },
    getwhiteShift (val) {
      this.$axios.get(this.$config['searchDay'], {
        params: {
          skey: localStorage.getItem('auth'),
          counts: 10,
          page: val || 1,
          starttime: this.time,
          fullname: this.groupsearch,
          userId: this.groupname1

        }
      }).then((res) => {
        for (var i of res.data.content.ships) {
          i.usernames = i.fullname
          if (i.stafftime) {
            i.stafftime = i.stafftime.split(',')

          } else {
            i.stafftime = []
          }
        }
        this.totalPage = res.data.content.shipSize
        this.whiteShift = res.data.content.ships
      })
    },
    getData (val) {
      if (this.plantabs == 'first') {
        this.getNight(val)
      } else if (this.plantabs == 'second') {
        this.getwhiteShift(val)
      }
    },
    changeWidth (val) {
      this.www = val
    },
    manipulate (s, id) {

      var doing = s.split('-')
      var item = this.nightShift[doing[1]]
      if (doing[0] == 'edit') {
        this.adddialog = true
        this.ddid = item.d_id
        this.content = 'edit'
      }
      if (doing[0] == 'look') {
        this.adddialog = true
        this.content = 'detail'
        this.ddid = item.d_id
      }
    },
    handleClick (tab, event) {
      this.sos = []
      this.getNewData()
      this.dutyname = ''
      this.time = ''
    },
    handleSizeChange (val) {
      this.getData(val)
    },
    handleCurrentChange (val) {
      this.getData(val)
    },
    handleCurrentChange1 (val) {
      this.getData(val)
    },
    deleteRow (index, rows) {
      var item = this.whiteShift[index]

      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$axios.get(this.$config['deleteDaySchedule'], {
          params: {
            skey: localStorage.getItem('auth'),
            d_id: item.d_id
          }
        }).then((res) => {
          this.$alert('删除成功!', '提示').then(() => {
            this.getwhiteShift()
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })

    },
    close () {
      this.adddialog = false
      this.$router.push('/index/duty/dutycommand')
      this.asd = false

    },
    add () {
      this.content = 'addWhite'
      this.adddialog = true
    },
    addDuty () {
      this.content = 'addDuty'
      this.adddialog = true
    },
    save (row) {
      if (this.endTime < this.startTime) {
        this.$alert('结束时间不能小于开始时间', '提示')
      }
      var arr = []
      var user_id = ''
      if (row.fullname !== row.usernames) {
        user_id = row.usernames
      } else {
        user_id = row.userId
      }
      arr.push({
        userId: user_id,
        stafftime: row.stafftime.join(','),
        starttime: row.starttime,
        endtime: row.endtime,
        d_id: row.d_id
      })

      this.$axios.get(this.$config['editDay'], {

        params: {
          skey: localStorage.getItem('auth'),
          dataList: JSON.stringify(arr)
        }
      }).then((res) => {
        this.$alert('保存成功', {
          callback: action => {

            // this.getwhiteShift()

          }
        })
      })
    },
    update () {
      this.adddialog = false
      this.getData()
    },
    timeChange () {
      this.getData(1, this.time)
    },
    reGetData: function (val) {
      this.getData()

    },
    dpChanges () {
      this.dutyname = this.groupname
      this.getData(1, this.dutyname)

    },
    dpChanges1 () {
      this.getData(1)
    },
    dgChanges () {
      this.getData(1, this.groupxname)
    },
    search1 (val) {
      this.dutyname = val
      this.getData(1)
    },
    cleared () {
      this.searchGroup()
    },
    // changeWidth (res) {
    //   this.dialogWidth = res
    // },
    uploadSuccess (res) {
      this.$message({
        type: 'success',
        message: '上传成功'
      })
    },
    uploadRemove: function (res) {

    },
    handlePreview (file) {
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 12 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeUpload1 (file) {
      this.uploadobj.filename = file.name
      this.uploadobj.busId = 1
      return true
    },
    beforeUpload (file) {
      this.uploadobj.busId = 0
      this.uploadobj.filename = file.name
      return true
    },
    actived (index, key) {
      if (this[key] == index) {
        this[key] = -1
        return false
      }
      this[key] = index
      // this.fheight= this.$refs.ele[index].clientHeight+'px'
    },
    // asdasd (index) {
    //   this.level1 = index
    // },

  }
}
